package com.lsj.filter;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.security.sasl.AuthenticationException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class VerifyCodeFilter extends GenericFilter {
    private String defaultFilterProcessUrl = "/doLogin";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req =(HttpServletRequest) servletRequest;
        HttpServletResponse resp =(HttpServletResponse) servletResponse;
        //判断是否为post请求且请求url是否为/doLogin
        if("POST".equals(req.getMethod()) && defaultFilterProcessUrl.equals(req.getServletPath())){
            //获取验证码
            String requestCaptcha =  req.getParameter("code");//获取从页面登录输入的验证码
            String  genCaptcha = (String)req.getSession().getAttribute("index_code");
            if(StringUtils.isEmpty(requestCaptcha)){
                throw new AuthenticationException("验证码不能为空");
            }
            if(!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())){
                throw new AuthenticationException("验证码错误");
            }
        }
        filterChain.doFilter(req,resp);
    }
}
